package cn.laike.modules.wechat.controller;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import cn.laike.common.utils.FileUtils;
import cn.laike.common.utils.PageUtils;
import cn.laike.common.utils.R;
import cn.laike.common.utils.RedisUtils;
import cn.laike.common.utils.mp.MpUtils;
import cn.laike.common.validator.ValidatorUtils;
import cn.laike.modules.dev.entity.CityEntity;
import cn.laike.modules.dev.entity.ConfigEntity;
import cn.laike.modules.dev.utils.DevCacheUtils;
import cn.laike.modules.dev.utils.DevUtils;
import cn.laike.modules.dev.utils.MpCacheUtils;
import cn.laike.modules.sys.shiro.ShiroUtils;
import cn.laike.modules.wechat.entity.WechatEntity;
import cn.laike.modules.wechat.service.WechatService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



/**
 * 公众号管理
 *
 * @author ziye
 * @email 524748907@qq.com
 * @date 2019-01-04 14:04:03
 */
@RestController
@RequestMapping("wechat/wechat")
public class WechatController {
    @Autowired
    private WechatService wechatService;
    
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("wechat:wechat:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = wechatService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    @RequiresPermissions("wechat:wechat:info")
    public R info(){
    	String redirect_uri = "http://laike.hbweiyinqing.cn/api/mp/redirect?uid="+ShiroUtils.getUserId();
    	//String redirect_uri = "http://182s163a59.imwork.net/admin/api/mp/redirect?uid="+ShiroUtils.getUserId();
    	ConfigEntity config = DevCacheUtils.getConfig(ShiroUtils.getUserId());
    	WechatEntity wechat = null;
    	if(config != null && StringUtils.isNotEmpty(config.getAppId())){
    		wechat =  wechatService.getWechatEntity(config.getAppId());
    		if(wechat != null && wechat.getStatus() != null && wechat.getStatus() == 1){
    			return R.ok().put("wechat", wechat);
    		}
    		if(wechat == null){
        		wechat = new WechatEntity();
        	}
    		wechat.setAuthorizationAppid(config.getAppId());
    	}else{
    		if(wechat == null){
        		wechat = new WechatEntity();
        	}
    	}
    	
    	String pro_auth_code = MpCacheUtils.getPreAuthCode();
    	redirect_uri = URLEncoder.encode(redirect_uri);
		String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid="+MpUtils.appId+"&pre_auth_code="+pro_auth_code+"&redirect_uri="+redirect_uri;
		System.out.println(url);
		return R.ok().put("wechat", wechat).put("url", url).put("bind", StringUtils.isNotEmpty(pro_auth_code));
    }
    
    
    
    

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("wechat:wechat:save")
    public R save(@RequestBody WechatEntity wechat){
        wechatService.insert(wechat);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("wechat:wechat:update")
    public R update(@RequestBody WechatEntity wechat){
        ValidatorUtils.validateEntity(wechat);
        wechatService.updateAllColumnById(wechat);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("wechat:wechat:delete")
    public R delete(@RequestBody Integer[] ids){
        wechatService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }
    
    @RequestMapping("/getConfig")
    public R getConfig(){
    	WechatEntity config = getCatchConfig();
        return R.ok().put("config", config);
    }
    
    @RequestMapping("/saveConfig")
    public R saveConfig(@RequestBody WechatEntity wechat){
        if(StringUtils.isNotEmpty(wechat.getTemplateId())) {
        	String key = "wxa_config";
        	redisUtils.setObject(key, wechat);
        	return R.ok("保存成功");
        }else {
        	return R.error("请填写代码模版ID");
        }
    }
    
    /**
     * 1、为授权的小程序帐号上传小程序代码
     * @param ids
     * @return
     */
    @RequestMapping("/commit")
    public R commit(@RequestBody Integer[] ids){
    	WechatEntity config = getCatchConfig();
    	if(StringUtils.isNotEmpty(config.getTemplateId())) {
    		for (Integer id : ids) {
    			WechatEntity wechat = wechatService.selectById(id);
    			String accessToken = MpCacheUtils.getAuthorizerAccessToken(wechat.getAuthorizationAppid());
    			System.out.println("-------------------------");
    			System.out.println(accessToken);
    			MpUtils.modify_domain(accessToken);
    			MpUtils.setwebviewdomain(accessToken);
    			System.out.println("-------------------------");
    			JSONObject result = MpUtils.commit(accessToken, config.getTemplateId(), getExtJson(wechat), config.getUserVersion(), config.getUserDesc());
        		
        		wechat.setTemplateId(config.getTemplateId());
        		wechat.setUserVersion(config.getUserVersion());
        		wechat.setUserDesc(config.getUserDesc());
        		if(result.getString("errcode").equals("0")) {
        			wechat.setErrcode("1");
        			wechat.setErrmsg(result.getString("errmsg"));
        			wechatService.insertOrUpdate(wechat);
        		}else {
        			wechat.setErrcode("0");
            		wechat.setErrmsg(result.getString("errmsg"));
            		wechatService.insertOrUpdate(wechat);
        		}
        		wechatService.insertOrUpdate(wechat);
    		}
    		return R.ok();
    	}else {
        	return R.error("请完善开发配置");
        }
    }
    
    /**
     * 2、获取体验小程序的体验二维码
     * @param ids
     * @return
     */
    @RequestMapping("/get_qrcode")
    public R get_qrcode(Integer id){
    	WechatEntity wechat = wechatService.selectById(id);
    	if(StringUtils.isNotEmpty(wechat.getErrcode())) {
    		String filename = wechat.getAuthorizationAppid()+".jpg";
        	String filepath = DevUtils.getQrcodeResourceSavePath();
        	FileUtils.createDirectory(filepath);
        	MpUtils.get_qrcode(MpCacheUtils.getAuthorizerAccessToken(wechat.getAuthorizationAppid()), null, filepath, filename);
        	return R.ok().put("qrcode", "userfiles/qrcode/"+filename);
    	}else {
    		return R.error("请上传代码");
    	}
    	
    }
    
    /**
     * 5、将第三方提交的代码包提交审核（仅供第三方开发者代小程序调用）
     * @param ids
     * @return
     */
    @RequestMapping("/submit_audit")
    public R submit_audit(@RequestBody Integer[] ids){
		for (Integer id : ids) {
			WechatEntity wechat = wechatService.selectById(id);
			if(wechat.getErrcode().equals("1")) {
				String accessToken = MpCacheUtils.getAuthorizerAccessToken(wechat.getAuthorizationAppid());
				JSONObject category = MpUtils.get_category(accessToken);
				JSONObject param = new JSONObject();
				JSONArray categoryList = category.getJSONArray("category_list");
				for (int i = 0; i < categoryList.size(); i++) {
					JSONObject item = categoryList.getJSONObject(i);
					item.put("title", "首页");
					item.put("address", "pages/index/index");
					item.put("tag", "酒店");
				}
				param.put("item_list", categoryList);
				JSONObject result = MpUtils.submit_audit(accessToken,param);
	    		
				if(result.getString("errcode").equals("0")) {
	    			wechat.setErrcode("2");
	    			wechat.setErrmsg(result.getString("errmsg"));
	    			wechatService.insertOrUpdate(wechat);
	    			MpUtils.modify_domain(accessToken);
	    		}else {
	        		wechat.setErrmsg(result.getString("errmsg"));
	        		wechatService.insertOrUpdate(wechat);
	    		}
			}else {
				wechat.setErrmsg("审核失败,请上传代码");
        		wechatService.insertOrUpdate(wechat);
			}
			wechatService.insertOrUpdate(wechat);
		}
    	return R.ok();
    }
    /**
     * 9、发布已通过审核的小程序（仅供第三方代小程序调用）
     * @param ids
     * @return
     */
    @RequestMapping("/release")
    public R release(@RequestBody Integer[] ids){
    	WechatEntity config = getCatchConfig();
    	if(StringUtils.isNotEmpty(config.getTemplateId())) {
    		
    		for (Integer id : ids) {
    			WechatEntity wechat = wechatService.selectById(id);
    			String accessToken = MpCacheUtils.getAuthorizerAccessToken(wechat.getAuthorizationAppid());
    			JSONObject result = MpUtils.release(accessToken);
    			if(result.getString("errcode").equals("0")) {
	    			wechat.setErrcode("5");
	    			wechat.setErrmsg(result.getString("errmsg"));
	    			wechatService.insertOrUpdate(wechat);
	    		}else if(result.getString("errcode").equals("85019")) {
	    			wechat.setErrmsg("没有审核版本");
	    			wechatService.insertOrUpdate(wechat);
	    		}else if(result.getString("errcode").equals("85052")) {
	    			wechat.setErrcode("5");
	    			wechat.setErrmsg("小程序已发布！");
	    			wechatService.insertOrUpdate(wechat);
	    		}else {
	    			result = MpUtils.get_latest_auditstatus(accessToken);
	    			if(result.getString("errcode").equals("0")) {
	    				if(result.getString("status").equals("0")) {
	    					wechat.setErrcode("4");
	    	    			wechat.setErrmsg(result.getString("errmsg"));
	    				}else if(result.getString("status").equals("1")) {
	    					wechat.setErrcode("3");
	    					wechat.setErrmsg(result.getString("errmsg"));
	    				}else if(result.getString("status").equals("3")) {
	    					wechat.setErrcode("3");
	    					wechat.setErrmsg("已撤销");
	    				}else {
	    					wechat.setErrcode("2");
	    					wechat.setErrmsg("审核中");
	    				}
	    			}else {
	    				wechat.setErrmsg(result.getString("errmsg"));
	    			}
            		wechatService.insertOrUpdate(wechat);
	    		}
    		}
    		return R.ok();
    	}else {
    		return R.error("请填写代码模版ID");
    	}
    }
    
    private WechatEntity getCatchConfig() {
    	WechatEntity config = null;
    	String key = "wxa_config";
		Object result = redisUtils.getObject(key);
		if (result != null) {
			config = (WechatEntity)result;
		}else{
			config = new WechatEntity();
		}
		return config;
    }
    
    private String getExtJson(WechatEntity wechat) {
    	JSONObject extjson = new JSONObject(); 
		extjson.put("extEnable", "true");
		extjson.put("extAppid", wechat.getAuthorizationAppid()); 
		JSONObject ext = new JSONObject(); 
		ext.put("uid", wechat.getUid().toString()); 
		ext.put("tid", "1"); 
		extjson.put("ext", ext);
		return "\"" + extjson.toString() + "\"";
    }


}
